package nthu.web.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nthu.web.model.domain.Hadoop;
import nthu.web.model.domain.box.MemoBox;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

@SuppressWarnings("serial")
public class HadoopStorageControll extends ResourceController<byte[]>{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
		
		MemoBox memo = new MemoBox((long)101010,(long)100101,"test","fjalkdf<>, jkljk#$%&%*&^(&(");
		Hadoop hadoop = new Hadoop();
		try {
			hadoop.storeMemoBox(memo, "bear/memo.xml");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			JSONObject json = hadoop.getMemoBox("bear/memo.xml");
			PrintWriter out = response.getWriter();
			out.print("<html><body>");
			out.println("test");
			out.println(json.getLong("id"));
			out.println(json.getString("Content"));
			out.print("</body></html>");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
		/*response.setContentType("image/jpeg");
		PrintWriter out = response.getWriter();
		InputStream input = request.getInputStream();
		DataInputStream dis = new DataInputStream(input);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		IOUtils.copy(dis, bos);
		out.print(request.getParameter("fileName"));
		String url = "hdfs://localhost:9000/user/bear";
		Configuration conf = new Configuration();
		FileSystem fs = FileSystem.get(URI.create(url), conf);
		OutputStream ous = fs.create(new Path("bear"+"/"+"test.txt"),true);
		ous.write(bos.toByteArray());
		ous.flush();
		ous.close();*/

		
	}
}